package ro.asterix.business;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;

import ro.asterix.data.Oaspete;
import ro.asterix.interfaces.OaspeteManager;

public class OaspeteManagerImpl implements OaspeteManager {

	DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();
	/**
	 * getOaspeti() - Returns a list of Oaspeti() from the data store SPECIAL
	 * ATTENTION on declaring twice the DatastoreService
	 * 
	 * @author ETATARU
	 * @param n
	 *            /a
	 * @return List<Oaspete>
	 */
	@Override
	public List<Oaspete> getOaspeti() {
		// TODO return a list with stored guests
		/* Getting the Query */
		Query query = new Query("Oaspete").addSort("date",
				Query.SortDirection.DESCENDING);
//		/* Declaring the DatastoreService */
//		DatastoreService datastore = DatastoreServiceFactory
//				.getDatastoreService();
		/* Creating the List with the datastore items */
		List<Entity> oaspeti = datastore.prepare(query).asList(
				FetchOptions.Builder.withLimit(100));
		/* Attention needed!*/
		/* Local list. */
		List<Oaspete> oList = new ArrayList<Oaspete>();
		for (Entity localEntity : oaspeti) {
			Oaspete localOaspete;
			String surname = (String) localEntity.getProperty("prenume");
			String name = (String) localEntity.getProperty("nume");
			Date date = (Date) localEntity.getProperty("date");
			localOaspete = new Oaspete(name, surname, date);
			oList.add(localOaspete);
		}
		return oList;
	}

	/**
	 * save() - Persist the Oaspete object received as param
	 * 			after validation;
	 * @author ETATARU
	 * @param Oaspete
	 *            object
	 * @return void
	 * 
	 */
	@Override
	public void save(Oaspete o) throws BusinessValidationException {
		// TODO Obiectul de tip Oaspete ii introducem in DataStore
//		/* Declaring the DatastoreService */
//		DatastoreService datastore = DatastoreServiceFactory
//				.getDatastoreService();
		/* Declaring Entity object */
		Entity guestEntity = new Entity("Oaspete");
		/* Validate Name field. */
		if (o.getName().isEmpty()){
			throw new BusinessValidationException("Name cannot be empty!");
		}
		/* Validate Surname field. */
		if (o.getSurname().isEmpty()){
			throw new BusinessValidationException("Surname cannot be empty!");
		}
		/* Setting Entity object properties */
		guestEntity.setProperty("date", o.getCheckIn()); // Time stamp
		guestEntity.setProperty("prenume", o.getSurname()); // Surname
		guestEntity.setProperty("nume", o.getName()); // Family name
		/* Storing the object */
		datastore.put(guestEntity);
	}

}
